<?php

	echo $this->Html->css('addition-style');
	echo $this->Html->css('invoice-header');
	echo $this->Html->script('more');
	
?>
<script>
$(function() {
	
	function log( id, notes ) {
		$("#customer_id").val(id);
		$("#customer_notes").val(notes);
	}
 
	$( "#dCustomer" ).autocomplete({
		source: "../invoice_headers/getCustomers",
		minLength: 0,
		select: function( event, ui ) {
			
			log(ui.item.id, ui.item.notes);
			
		},
		change: function( event, ui ) {

			if (ui.item) {
				
				log(ui.item.id, ui.item.notes);
				$(event.target).autocomplete("close");
				
			} else {
				//From http://jsfiddle.net/EuXrP/
				var myInput = $(this);
			    
			    if (myInput.val() == "") {
			    	
			    	log("","");
			    	return false;
			    	
			    }
			    
			    var autocomplete = $(this).data("autocomplete");
			    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
				
			    autocomplete.widget().children(".ui-menu-item").each(function() {
			        //Check if each autocomplete item is a case-insensitive match on the input
			        var item = $(this).data("item.autocomplete");
			        if (matcher.test(item.label || item.value || item)) {
			            //There was a match, lets stop checking
			            autocomplete.selectedItem = item;
			            return;
			        }
			    });
			    //if there was a match trigger the select event on that match
			    //I would recommend matching the label to the input in the select event
			    if (autocomplete.selectedItem) {
			        autocomplete._trigger("select", event, {
			            item: autocomplete.selectedItem
			        });
			    //there was no match, clear the input
			    } else {
			        log("","");
			    }

			}
        
		}
		
	}).focus(function(){

		if ($(this).autocomplete("widget").is(":visible")) {
			return;
		}
		 $(this).data("autocomplete").search();
		 //return false;

	});

});

$(document).ready(function () {
		
	var idCount = 0;
    
    function logItem( element, id, price ) {
		$( "#InvoiceItemItemID" + element.toString()).val(id);
		$( "#InvoiceItemUnitPrice" + element.toString()).val(price);
		$( "#InvoiceItemDiscount" + element.toString()).val("");
		$( "#InvoiceItemQty" + element.toString()).val("");
		
		var theElement = $( "#InvoiceItemUnitPrice" + element.toString()).get(0);
		ThousandSeparate(theElement);

		if (id == "") {
			return;
		}	
		
		var customerId = $("#customer_id").val();
		$.ajax({ 
			url: '../invoice_headers/getCustomerDiscount',
			data: { 'customer': customerId, 'item': id },
			type: 'post',
			success: function(output) {
				var jsonObj = JSON.parse(output);
				var item_discount = jsonObj.discount;
				$( "#InvoiceItemDiscount" + element.toString()).val( item_discount);

			}
		});

	}
    
	$("#invoiceItemList").on('click', "#addRow", function () {
    	idCount++; 
		var new_row='<tr>' +
                    '<td class="invoiceItemListCol"><input name="data[InvoiceItem][' + idCount + '][item]" maxlength="40" type="text" id="InvoiceItemItem_' + idCount + '" class="form-control">' +
                    	'<input name="data[InvoiceItem][' + idCount + '][item_id]" maxlength="40" type="text" hidden="true" id="InvoiceItemItemID' + idCount + '"></td>' +
                    '<td class="invoiceItemListCol"><input name="data[InvoiceItem][' + idCount + '][unit_price]" type="text" disabled readonly="readonly" id="InvoiceItemUnitPrice' + idCount + '" class="form-control readonly"></td>' +
                    '<td class="invoiceItemListCol"><input name="data[InvoiceItem][' + idCount + '][item_discount]" type="text" disabled readonly="readonly" id="InvoiceItemDiscount' + idCount + '" class="form-control readonly"></td>' +
                    '<td class="invoiceItemListCol"><input name="data[InvoiceItem][' + idCount + '][qty]" type="text" id="InvoiceItemQty' + idCount + '" class="form-control"></td>' +
                    '<td class="invoiceItemListCol"><input name="data[InvoiceItem][' + idCount + '][line_price]" type="text" disabled readonly="readonly" id="InvoiceItemItemPrice' + idCount + '" class="form-control readonly"></td>' +
                    '<td class="invoiceItemListColAction">' +
                    '	<img src="<?php echo $this->webroot; ?>img/btnRemove.jpg" alt="Delete" width="20px" height="20px" class="deleteRow" id="deleteRow' + idCount + '" />' +
                    '</td>' +
            		'</tr>';

		$("#invoiceItemList").append(new_row);
		$( "[id^=InvoiceItemItem_]" ).autocomplete({
		source: "../invoice_headers/getItems",
		minLength: 0,
		select: function( event, ui ) {
			
			var itemId = $(this).attr('id').substring(16);
			logItem(itemId, ui.item.id, ui.item.price);
			
		},
		change: function( event, ui ) {

			var itemId = $(this).attr('id').substring(16);

			if (ui.item) {
			
				logItem(itemId, ui.item.id, ui.item.price);
				$(event.target).autocomplete("close");
				
			} else {				
				//From http://jsfiddle.net/EuXrP/
				var myInput = $(this);
			    
				if (myInput.val() == "") {
			    	
			    	logItem(itemId, "", "");
			    	return false;
			    	
			    }
			    
			    var autocomplete = $(this).data("autocomplete");
			    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
				
				autocomplete.widget().children(".ui-menu-item").each(function() {
			        //Check if each autocomplete item is a case-insensitive match on the input
			        var item = $(this).data("item.autocomplete");
			        if (matcher.test(item.label || item.value || item)) {
			            //There was a match, lets stop checking
			            autocomplete.selectedItem = item;
			            return;
			        }
			    });
			    //if there was a match trigger the select event on that match
			    //I would recommend matching the label to the input in the select event
			    if (autocomplete.selectedItem) {
			        autocomplete._trigger("select", event, {
			            item: autocomplete.selectedItem
			        });
			    //there was no match, clear the input
			    } else {
			    	
			    	logItem(itemId, "", "");
			    	
				}

			}
        
		}
	
		}).focus(function(){

			if ($(this).autocomplete("widget").is(":visible")) {
				return;
			}
			 $(this).data("autocomplete").search();

		});
	
	});

	$("#invoiceItemList").on('click', ".deleteRow", function () {
         $(this).parent().parent().remove();
     });

	$(document).on('blur',"[id^=InvoiceItemQty]", function() {
  		var itemId = $(this).attr('id').substring(14);
  		computeItemTotal( itemId );

	});

	function computeItemTotal( element ) {
  		var unitPrice = $( "#InvoiceItemUnitPrice" + element.toString() ).val();
		var unitDiscount = $( "#InvoiceItemDiscount" + element.toString()).val();
		
		unitPrice = unitPrice.replace(',','');
		
  		var itemDiscountedPrice =  unitPrice - ( unitPrice * (parseFloat( unitDiscount ) / 100 ) );
		var itemQuantity = $( "#InvoiceItemQty" + element.toString() ).val();
		var itemTotal = parseFloat( itemDiscountedPrice * itemQuantity).toFixed(2);

		$( "#InvoiceItemItemPrice" + element.toString()).val( itemTotal );
  		var theElement = $( "#InvoiceItemItemPrice" + element.toString()).get(0);
		
  		ThousandSeparate(theElement);
	}

	$("#addRow").click();

  });
</script>

<div id="main-form">

	<?php
	echo $this->Form->create();
	?>

	<div class="top-group">
    	<div class="form-group">
        	<label for="">Invoice No</label>
            <?php echo $this->Form->input('InvoiceHeader.invoice_no', array('label' => false, 'type' => 'text', 'class' => 'form-control')); ?>
        	<label for="">Date</label>
            <?php //echo $this->Form->input('InvoiceHeader.entry_date', array('id' => 'datepicker', 'label' => false, 'type' => 'text', 'class' => 'form-control', 'default' => date('m/d/Y'))); ?>
			<?php //echo $this->Form->input('InvoiceHeader.entry_date', array('id' => 'datepicker', 'label' => false, 'type' => 'text', 'class' => 'form-control', 'defaultValue' => "getCurrentDate()")); ?>
			<?php echo $this->Form->input('InvoiceHeader.entry_date', array('id' => 'datepicker', 'label' => false, 'type' => 'text', 'class' => 'form-control')); ?>
		</div>
	</div>

	<div class="four-columns">
		<div class="four-columns-col">
			<label for="">Shipping Notes</label>
			<?php echo $this->Form->textarea('InvoiceHeader.shipping_notes', array('label' => false, 'type' => 'text', 'class' => 'form-control')); ?>
		</div>
		<div class="four-columns-col">
			<label for="">Tax Terms</label>
			<?php echo $this->Form->text('InvoiceHeader.tax_terms', array('label' => false, 'type' => 'text', 'class' => 'form-control')); ?>
			<label for="">Terms</label>
			<?php echo $this->Form->input('InvoiceHeader.term_id', array('label' => false,'div' => 'select-input')); ?>
		</div>
		<div class="four-columns-col">
			<label for="">P.O.</label>
			<?php echo $this->Form->text('InvoiceHeader.purchase_order_no', array('label' => false, 'type' => 'text', 'class' => 'form-control')); ?>
			<label for="">Discount</label>
			<?php echo $this->Form->text('InvoiceHeader.discount', array('label' => false, 'type' => 'text', 'class' => 'form-control')); ?>
		</div>
		<div class="four-columns-col">
			<label for="">Customer</label>
			<?php 
			echo $this->Form->text('customerName', array("id" => "dCustomer", 'class' => 'form-control')); 
			echo $this->Form->text('InvoiceHeader.customer_id', array("id" => "customer_id", "hidden" => "true"));
			echo $this->Form->textarea("customerNotes", array("id" => "customer_notes", "readonly" => "true", 'class' => 'form-control readonly'));
			?>

		</div>
	</div>
	
	<div style="clear: both;"></div>

	<div class="top-group">
	<table id="invoiceItemList">
		<tr>
			<td class="invoiceItemListCol">Item</td>
			<td class="invoiceItemListCol">Unit Price</td>
			<td class="invoiceItemListCol">Item Discount</td>
			<td class="invoiceItemListCol">Quantity</td>
			<td class="invoiceItemListCol">Total Price</td>
		    <td class="invoiceItemListColAction">
				<img src="<?php echo $this->webroot; ?>img/btnAdd.jpg" alt="Add" width="20px" height="20px" id="addRow" />
			</td>
		</tr>
	</table>
	</div>

	<div class="top-group">
    	<div class="form-group">
			<button type="submit" class="btn btn-primary" value="save">save</button>
		</div>
	</div>
	
</div>
<script>
$(document).ready(function () { $("#datepicker").val( getCurrentDate() );});
</script>